/*  This file is a part of JJSched source code
    JJSched - Java Jabber Scheduler - a simple Jabber scheduling application
    Copyright (C) 2008 Cestmir "CZestmyr" Houska

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/> */

package czestmyr.jjsched;

import java.lang.*;
import java.nio.charset.*;
import java.nio.*;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.util.*;

/**
 * Handles the connection to the XMPP server.
 */
public class Connector{
    /**
     * Constructor.
     *
     * @param   conn    Information about the connection to the XMPP server
     */
    Connector(XMPPConnection conn, DatabaseConnector dbc){
        connection = conn;
		theDBConnector = dbc;
    }

    /**
     * Tries to connect to the XMPP server
     * @throws  Exception   In case of failed attempt to connect to the XMPP server
     */
    public void connect() throws Exception{
        connection.connect();
    }

    /**
     * Disconnects from the XMPP server
     */
    public void disconnect(){
        connection.disconnect();
    }

    /**
     * Tries to login to the XMPP server with the given username and password.
     *
     * @param   userName    The username of the user to login
     * @param   password    The password of the given user
     * @throws  Exception   In case of unsuccessful login
     */
    public void login(String userName, String password) throws Exception{
        connection.login(userName, password);

        userWithoutResource = StringUtils.parseName(connection.getUser()) + "@" +
                              StringUtils.parseServer(connection.getUser());
    }

    /**
     * Sends a message through the established XMPP connection to the given user.
     * The user has to be specified by his/her Jabber ID.
     *
     * @param   message The message to be sent
     * @param   user    Jabber ID of the recipient of the message. Can be "console" to output via console
     */
    public void sendMessage(String message, String user){
		if (user.equals("console")) {
			System.out.println(message);
			return;
		}

		//Debug
		System.out.println("sending message");
		System.out.println(message);

		//Try to encode the message to the user's preffered charset
		try {	
			//String encoding = theDBConnector.getUserCharset(user);
			//message = Charset.forName(encoding).encode(ByteBuffer.wrap(message.getBytes(encoding)).asCharBuffer()).toString();
		} catch (Exception e) {
			//Do nothing - the message will remain in UTF-8
			//DEBUG: print the exception
			System.out.println(e.getMessage());
		}

		//Debug
		System.out.println("encoded message");
		System.out.println(message);

        Message m = new Message(user, Message.Type.chat);
        m.setBody(message);
        m.setFrom(userWithoutResource);
        connection.sendPacket(m);
    }

    /**
     * Adds a message listener to the underlying XMPP connection.
     *
     * @param   p   The packet listener that will be notified of an incoming message
     */
    public void addMessageListener(PacketListener p){
        connection.addPacketListener(p, new PacketTypeFilter(Message.class));
    }

    /** Connection to the XMPP server */
    private XMPPConnection connection;
    /** User name of the current connection (in form user@server - without the resource) */
    private String userWithoutResource;
	/** The database connector class */
	private DatabaseConnector theDBConnector;
}
